package com.gwtplatform.samples.hplace.client.breadcrumbs;

import com.google.gwt.user.client.ui.HasHTML;
import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.View;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.jsorm.JsonSerializer;
import com.gwtplatform.samples.hplace.client.HasWidget;
import com.gwtplatform.samples.hplace.client.attacher.RootPanelAttacher;
import com.gwtplatform.samples.hplace.client.breadcrumbs.BreadcrumbsPresenterImpl.BreadcrumbsBinder;

import java.util.ArrayList;

public class BreadcrumbsPresenterImpl extends GuitPresenter<BreadcrumbsBinder> implements
    BreadcrumbsPresenter {

    public static interface BreadcrumbsBinder extends GuitBinder<BreadcrumbsPresenterImpl> {
    }

    public static interface BackeableSerializer extends JsonSerializer<Backeable<Integer>> {
    }

    BackeableSerializer serializer;
    RootPanelAttacher attacher;

    @ViewField
    HasHTML navegation;
    
    @ViewField
    HasWidget panel;
    
    @Inject
    public BreadcrumbsPresenterImpl(BackeableSerializer serializer, RootPanelAttacher attacher) {
        this.serializer = serializer;
        this.attacher = attacher;
    }

    @Override
    protected void initialize() {
        attacher.attach(getView());
    }

    @Override
    public void buildNavegation(String name, View view, Backeable<Integer> backeable) {
        panel.setWidget(view);

        ArrayList<String> tokens = new ArrayList<String>();
        ArrayList<String> names = new ArrayList<String>();

        if (backeable != null) {
            tokens.addAll(backeable.getBackTokens());
            names.addAll(backeable.getNames());
        }

        names.add(name);
        tokens.add(placeManager.getCurrentToken());

        StringBuilder sb = new StringBuilder();
        int size = names.size();
        for (int n = 0; n < size; n++) {
            if (sb.length() > 0) {
                sb.append(" > ");
            }

            sb.append("<a href='#");
            sb.append(tokens.get(n));
            sb.append("'>");
            sb.append(names.get(n));
            sb.append("</a>");
        }

        navegation.setHTML(sb.toString());
    }
}
